import Koa from "koa";
import cors from "@koa/cors";
import bodyParser from "koa-body";
import serve from "koa-static";
import router from "./routes";
import env from "./config/env";
import path from "path";

const app = new Koa();

// 中间件
app.use(cors());
app.use(bodyParser());
// 静态资源目录
app.use(serve(path.join(__dirname, "..", "public")));
// 错误处理中间件
app.use(async (ctx, next) => {
  try {
    await next();
  } catch (error: any) {
    ctx.status = error.status || 500;
    ctx.body = {
      code: ctx.status,
      message: error.message || "Internal Server Error",
    };

    // 开发环境下输出错误堆栈
    if (env.NODE_ENV === "development") {
      console.error("Error:", error);
    }
  }
});

// 路由
app.use(router.routes());
app.use(router.allowedMethods());

// 启动服务器
const PORT = env.PORT;

app.listen(PORT, () => {
  console.log(`🚀 Server running on port ${PORT}`);
  console.log(`📊 Environment: ${env.NODE_ENV}`);
  console.log(`🔗 Health check: http://localhost:${PORT}/health`);
  console.log(`👋 Hello World: http://localhost:${PORT}/`);
});

export default app;
